import re
import requests


class OnlineInfo:
    def __init__(self):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/89.0.4389.114 Safari/537.36 '
        }

    @staticmethod
    def merge_dict(dic1, dic2):
        """合并字典，同时间戳则建立列表"""
        for key in dic1:
            if dic2.get(key):
                dic2[key] = [dic2[key]]
                dic2[key].append(dic1[key])
            else:
                dic2[key] = [dic1[key]]
        return dic2

    def get_music_info_163(self, item_name):
        """搜索歌曲，获得id"""
        url = 'https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s={' + item_name + \
              '}&type=1&offset=0&total=true&limit=2'
        try:
            res = requests.get(url, headers=self.headers)
        except Exception as e:
            print(e)
            return {"id": 0, "name": '无', "artist": '无'}
        res_js = res.json()
        music = res_js["result"]['songs'][0]
        music_id = music['id']
        music_name = music['name']
        music_artists = music['artists']
        music_artist = ''
        for artist in music_artists:
            if music_artist != '':
                music_artist += '/' + artist['name']
            else:
                music_artist += artist['name']
        return {"id": music_id, "name": music_name, "artist": music_artist}

    def get_lyric_163(self, music_id):
        """根据歌曲id获取歌词"""
        def timestamp_to_dict(lrc_list):
            # 时间戳正则
            func = re.compile("\\[.*?]")
            # 根据时间戳，转换成字典
            _lrc_dict = {}
            for _i in lrc_list:
                if func.search(_i) is None:
                    continue
                lrc_time = func.search(_i).group()
                lrc_text = func.sub('', _i)
                lrc_text = ' '.join(lrc_text.split())
                _lrc_dict[lrc_time] = lrc_text
            return _lrc_dict

        if music_id == 0:
            return ''
        lrc_url = 'https://music.163.com/api/song/lyric?id=' + str(music_id) + '&lv=1&kv=1&tv=-1'
        try:
            lyric_get = requests.get(lrc_url, headers=self.headers)
        except Exception as e:
            print(e)
            return ''

        try:
            # 获取歌词
            lyric_raw = lyric_get.json()['lrc']['lyric']
            lyric_zh = lyric_get.json()['tlyric']['lyric']
        except KeyError:
            print(lyric_get.text)
            return ''

        print('获取成功！')
        if lyric_zh == '':
            # 无翻译，返回原始歌词
            return lyric_raw

        # 以换行符分割
        lrc_list_zh = lyric_zh.splitlines()
        lrc_list_raw = lyric_raw.splitlines()

        # 提取翻译作者，限网易云
        by = ''
        if lrc_list_zh[0].find('by:') != -1:
            by = lrc_list_zh.pop(0)
            by = by + '\n'

        # 根据时间戳，转换成字典
        lrc_dict_zh = timestamp_to_dict(lrc_list_zh)
        lrc_dict_raw = timestamp_to_dict(lrc_list_raw)

        lrc_dic_merge = self.merge_dict(lrc_dict_zh, lrc_dict_raw)
        # 时间戳排序
        list_up = sorted(lrc_dic_merge)
        lrc_output = by
        # 根据时间戳顺序重构歌词
        for i in list_up:
            if type(lrc_dic_merge[i]) is str:
                lrc_output = lrc_output + i + lrc_dic_merge[i] + '\n'
            elif lrc_dic_merge[i][0] == '':
                lrc_output = lrc_output + i + lrc_dic_merge[i][0] + '\n'
            else:
                lrc_output = lrc_output + i + lrc_dic_merge[i][0] + '\n' + i + lrc_dic_merge[i][-1] + '\n'
        return lrc_output

    def get_music_comment_163(self, music_id):
        """获取评论"""
        url = f'https://music.163.com/api/v1/resource/comments/R_SO_4_{music_id}?limit=20&offset=0'
        try:
            info_get = requests.get(url, headers=self.headers)
        except requests.exceptions.ConnectionError:
            print('网络连接失败')
            return {"LrcMusicPlayer": "网络连接失败"}
        print('获取成功！')
        hot_comments_list = info_get.json()["hotComments"]
        user_dict = {}
        if hot_comments_list:
            for item in hot_comments_list:
                name = item["user"]["nickname"]
                user_dict[name] = item["content"]
        else:
            comments_list = info_get.json()["comments"]
            for item in comments_list:
                name = item["user"]["nickname"]
                user_dict[name] = item["content"]
        return user_dict


online_info = OnlineInfo()
